package com.atgugu.flink.chapter09;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/4/9 8:57
 */
public class Flink02_CEP_Loop {
    
    
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 1. 先有一个流
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1000L, 1),
                new WaterSensor("sensor_2", 2000L, 2),
                new WaterSensor("sensor_1", 3000L, 3),
                new WaterSensor("sensor_1", 4000L, 4),
                new WaterSensor("sensor_2", 5000L, 5),
                new WaterSensor("sensor_1", 6000L, 6)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        // 2. 定制模式(指定规则)
        Pattern<WaterSensor, WaterSensor> pattern = Pattern
            .<WaterSensor>begin("s1")
            .where(new SimpleCondition<WaterSensor>() {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "sensor_1".equals(value.getId());
                }
            })
            //            .times(2);
            //            .times(2, 4);  // 2次或3次或4次
            //            .timesOrMore(2);  // 2次或3次或4次或.....
            .oneOrMore(); // .timesOrMore(1)
        
        
        // 3. 把模式作用到流上, 得到一个模式流
        PatternStream<WaterSensor> ps = CEP.pattern(stream, pattern);
        // 4. 从模式流取出匹配到的数据
        ps
            .select(new PatternSelectFunction<WaterSensor, String>() {
                // map: key是前面定义模式的 模式名字
                @Override
                public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                    return pattern.get("s1").toString();
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
}
